﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialPortModbus
{
    public partial class serialtest : Form
    {
        private SerialPort ComDevice = new SerialPort();
        private SerialPort EndDevice = new SerialPort();
        public serialtest()
        {
            InitializeComponent();
            init();
        }
        public void init()
        {
            btnSend.Enabled = false;
            cbbComList.Items.AddRange(SerialPort.GetPortNames());
            if (cbbComList.Items.Count > 0)
            {
                cbbComList.SelectedIndex = 0;
            }
            cbbBaudRate.SelectedIndex = 5;
            cbbDataBits.SelectedIndex = 0;
            cbbParity.SelectedIndex = 0;
            cbbStopBits.SelectedIndex = 0;
            ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件

            comboBox5.Items.AddRange(SerialPort.GetPortNames());
            if (comboBox5.Items.Count > 0)
            {
                comboBox5.SelectedIndex = 0;
            }
            comboBox4.SelectedIndex = 5;
            comboBox3.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            comboBox1.SelectedIndex = 0;
            EndDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (cbbComList.Items.Count <= 0)
            {
                MessageBox.Show("没有发现串口,请检查线路！");
                return;
            }

            if (ComDevice.IsOpen == false)
            {
                ComDevice.PortName = cbbComList.SelectedItem.ToString();
                ComDevice.BaudRate = Convert.ToInt32(cbbBaudRate.SelectedItem.ToString());
                ComDevice.Parity = (Parity)Convert.ToInt32(cbbParity.SelectedIndex.ToString());
                ComDevice.DataBits = Convert.ToInt32(cbbDataBits.SelectedItem.ToString());
                ComDevice.StopBits = (StopBits)Convert.ToInt32(cbbStopBits.SelectedItem.ToString());
                try
                {
                    ComDevice.Open();
                    btnSend.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                btnOpen.Text = "关闭串口";
            }
            else
            {
                try
                {
                    ComDevice.Close();
                    btnSend.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                btnOpen.Text = "打开串口";
            }

            cbbComList.Enabled = !ComDevice.IsOpen;
            cbbBaudRate.Enabled = !ComDevice.IsOpen;
            cbbParity.Enabled = !ComDevice.IsOpen;
            cbbDataBits.Enabled = !ComDevice.IsOpen;
            cbbStopBits.Enabled = !ComDevice.IsOpen;

        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (comboBox5.Items.Count <= 0)
            {
                MessageBox.Show("没有发现串口,请检查线路！");
                return;
            }

            if (EndDevice.IsOpen == false)
            {
                EndDevice.PortName = comboBox5.SelectedItem.ToString();
                EndDevice.BaudRate = Convert.ToInt32(comboBox4.SelectedItem.ToString());
                EndDevice.Parity = (Parity)Convert.ToInt32(comboBox1.SelectedIndex.ToString());
                EndDevice.DataBits = Convert.ToInt32(comboBox3.SelectedItem.ToString());
                EndDevice.StopBits = (StopBits)Convert.ToInt32(comboBox2.SelectedItem.ToString());
                try
                {
                    EndDevice.Open();
                    btnSend.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                button1.Text = "关闭串口";
            }
            else
            {
                try
                {
                    EndDevice.Close();
                    btnSend.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                button1.Text = "打开串口";
            }

            comboBox1.Enabled = !EndDevice.IsOpen;
            comboBox2.Enabled = !EndDevice.IsOpen;
            comboBox3.Enabled = !EndDevice.IsOpen;
            comboBox4.Enabled = !EndDevice.IsOpen;
            comboBox5.Enabled = !EndDevice.IsOpen;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] sendData = null;
            try
            {
                byte addr= byte.Parse(txtAddr.Text);
                ushort addrData = ushort.Parse(txtDataAddr.Text);
                ushort addrLen = ushort.Parse(txtDataLen.Text);
                if (comboBox6.SelectedItem.ToString()=="03")
                {
                    sendData= MyModbus.GetReadFrame(addr, 0x03, addrData, addrLen);
                }
            }
            catch (Exception ex)
            {
                AddContent(ex.ToString());
                throw;
            }
            //if (rbtnSendHex.Checked)
            //{
            //    sendData = strToHexByte(txtSendData.Text.Trim());
            //}
            //else if (rbtnSendASCII.Checked)
            //{
            //    sendData = Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
            //}
            //else if (rbtnSendUTF8.Checked)
            //{
            //sendData = Encoding.UTF8.GetBytes(txtSendData.Text.Trim());
            //}
            //else if (rbtnSendUnicode.Checked)
            //{
            //sendData = Encoding.Unicode.GetBytes(txtSendData.Text.Trim());
            //}
            //else
            //{
            //    sendData = Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
            //}

            if (this.SendData(sendData))//发送数据成功计数
            {
                AddContent("发送指令："+ MyModbus.ByteArray2BinaryStr(sendData)+MyModbus.ToHexString(sendData));
            }
            else
            {

            }

        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        public bool SendData(byte[] data)
        {
            if (ComDevice.IsOpen)
            {
                try
                {
                    ComDevice.Write(data, 0, data.Length);//发送数据
                    return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("串口未打开", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return false;
        }
        byte[] datas = new byte[0];
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] ReDatas = new byte[ComDevice.BytesToRead];
            EndDevice.Read(ReDatas, 0, ReDatas.Length);//读取数据
            this.AddData(ReDatas);//输出数据
        }

        private void btnbuf_Click(object sender, EventArgs e)
        {
            byte[] ReDatas = new byte[] { 0,1,1,1,1,1,1,1};
            List<byte> lists = new List<byte>();
            lists.AddRange(datas);
            lists.AddRange(ReDatas);
            //byte[] live = dataByte.Skip(2053).Take(4).ToArray();
            //tfModel.LiveTime = BitConverter.ToSingle(dataByte, 2053);
            //byte[] data = new byte[datas.Length + ReDatas.Length];
            //Buffer.BlockCopy(datas, 0, data, 0, datas.Length);
            //Buffer.BlockCopy(ReDatas, 0, data, datas.Length, ReDatas.Length);
            datas = lists.ToArray() ;
            
        }
        private void btndel_Click(object sender, EventArgs e)
        {
            datas = datas.Skip(2).ToArray();
        }
        private void Send_DataReceived(object sender, SerialDataReceivedEventArgs e) {

            byte[] ReDatas = new byte[ComDevice.BytesToRead];
            ComDevice.Read(ReDatas, 0, ReDatas.Length);//读取数据
            this.AddData(ReDatas);//输出数据
        }
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="data">字节数组</param>
        public void AddData(byte[] data)
        {
            //if (rbtnHex.Checked)
            //{
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.AppendFormat("{0:x2}" + " ", data[i]);
            }
            AddContent(sb.ToString().ToUpper());
            //}
            //else if (rbtnASCII.Checked)
            //{
            //    AddContent(new ASCIIEncoding().GetString(data));
            //}
            //else if (rbtnUTF8.Checked)
            //{
            //AddContent(new UTF8Encoding().GetString(data));
            //}
            //else if (rbtnUnicode.Checked)
            //{
            //    AddContent(new UnicodeEncoding().GetString(data));
            //}
            //else
            //{ }

            //lblRevCount.Invoke(new MethodInvoker(delegate
            //{
            //    lblRevCount.Text = (int.Parse(lblRevCount.Text) + data.Length).ToString();
            //}));
        }


        /// <summary>
        /// 输入到显示区域
        /// </summary>
        /// <param name="content"></param>
        private void AddContent(string content)
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                //if (chkAutoLine.Checked && txtShowData.Text.Length > 0)
                //{
                    txtShowData.AppendText("\r\n");
                //}
                txtShowData.AppendText(content); 
            }));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            byte[] _rec = Encoding.Default.GetBytes(txtSendData.Text);
            int _reclen = _rec.Length;
            byte reccrcL = _rec[_reclen - 1];//取接收到的报文  校验码低位
            byte reccrcH = _rec[_reclen - 2];//取校验码高位
            ushort crc = MyModbus.CRC16(_rec, 0, _reclen-3);//重新校验报文
            if (reccrcL == MyModbus.WORD_LO(crc) && reccrcH == MyModbus.WORD_HI(crc))//比对校验码
            {
                byte fun = _rec[1];//功能码
                if (fun == 0x03)//modbus03功能码
                {
                    byte databyteNum = _rec[2];//接收字节数

                    AddContent(databyteNum.ToString());
                }
            }

        }

        private void Hex2Ten_Click(object sender, EventArgs e)
        {
            AddContent(Convertor.Hex2Ten(txtAddr.Text));
        }

        private void Ten2Hex_Click(object sender, EventArgs e)
        {
            AddContent(Convertor.Ten2Hex(txtAddr.Text));
        }

    }
}
